﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;


namespace Tornado
{
    public class PasswordTextbox: TextBox
    {
        public PasswordTextbox()
        {
            MaxLength = 4;
            this.Text = "0";
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        protected override void OnTextChanged(EventArgs e)
        {
            string s = Text;

            if (!Regex.IsMatch(s, "$\\d*^"))
            {
                foreach (char c in Text)
                {
                    if (!Char.IsDigit(c))
                    {
                        s = s.Replace("" + c, "");
                    }
                }
                Text = s;
            }


            base.OnTextChanged(e);
        }
        protected override void OnValidated(EventArgs e)
        {
            try
            {
                int.Parse(Text);
            }
            catch
            {
                this.Text = "0";
            }
            base.OnValidated(e);
        }
    }
}
